app.service('Template', ['$rootScope', 'backendSrv', function($rootScope, backendSrv){
        this.templates =  {};
        this.answers = {};

        var self = this;

        this.getTemplate =  function(name){
            templates[name]
        },
        //TODO to be modified to save/load from backend service
        this.getAnswers =  function(name){
            if(!self.answers[name]){
                self.answers[name] = {}
            }
            return self.answers[name]
        };

        this.loadTemplate = function(name){
            if(self.templates[name]){ 
                $rootScope.$broadcast('template.load', name, self.templates[name]);
                return;
            }
            backendSrv.getTemplate(name, function(data){
                self.templates[name] = data
                $rootScope.$broadcast('template.load',name, data)
            });
        };
}]);

app.controller('templateCtrl',['$scope','$http','backendSrv', 'Template', function($scope, $http, backendSrv, Template){
    var tplName = "reg_questionnaire"

    $scope.$on('template.load', function(event,name , template){
        $scope.template = template
    });
    $scope.$on('answers.load', function(event, answers){
        $scope.answers = answers
    });

    Template.loadTemplate(tplName)


    $scope.answers = Template.getAnswers(tplName)


    /*save answers json after validation*/
    $scope.saveAnswers = function(){
        backendSrv.sendCmd('/tpl/cmd', {Cmd:'save_answers', Data: $scope.answers}, 
            function(data){
                console.log("answers saved")
                console.log(data)
            }, 
            null)


    }
/*
*/
}]);

